#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#include "task_limit.h"

struct limit_st{
	int value;
	pthread_mutex_t mut;
	pthread_cond_t cond;
};

limit_t *limit_init(int initval)
{
	struct limit_st *me;
	me = malloc(sizeof(*me));
	if(me == NULL)
	{
		return NULL;
	}
	me->value = initval;
	pthread_mutex_init(&me->mut, NULL);
	pthread_cond_init(&me->cond, NULL);
	return me;
}

int limit_add(limit_t *ptr, int size)
{
	struct limit_st *me = ptr;
	
	pthread_mutex_lock(&me->mut);
	me->value += size;
	pthread_cond_broadcast(&me->cond);
	pthread_mutex_unlock(&me->mut);

	return size;
}

int limit_sub(limit_t *ptr, int size)
{
	struct limit_st *me = ptr;
	
	pthread_mutex_lock(&me->mut);
	while (me->value < size) {
		pthread_cond_wait(&me->cond, &me->mut);
	}
	me->value -= size;
	pthread_mutex_unlock(&me->mut);
	
	return size;
}

int limit_destory(limit_t * ptr)
{
	struct limit_st *me = ptr;
	pthread_mutex_destroy(&me->mut);
	pthread_cond_destroy(&me->cond);
	free(me);
	return 0;
}
